import Core.MongoDB as MongoDB
import Core.Gadget as Gadget
import datetime
import pandas as pd

# 简单的根据pe pb peg筛股（peg因子库里没有，得先计算因子入库）

def GetMonthlyStock(Year, Month):
    database = MongoDB.MongoDB("10.13.38.25", "27017")
    datetime1 = datetime.datetime(Year, Month, 1)
    datetime1 = Gadget.ToUTCDateTime(datetime1)
    datetime2 = datetime.datetime(Year, Month+1, 1)
    datetime2 = Gadget.ToUTCDateTime(datetime2)
    #sz_index = database.find("Instruments", "Stock")#, datetime1,datetime2)
    pb_index = pd.DataFrame(database.find("Factor", "PriceBookLF", datetime1,datetime2))
    pb_table = pd.pivot_table(pb_index, values = 'Value', index = 'Symbol', columns = 'StdDateTime')
    pb_select = pb_table[pb_table[pb_table.columns[0]] < 0.8]
    pb_select.columns = ['pb']

    pe_index = pd.DataFrame(database.find("Factor", "PriceEarningOperatingProfitTTM", datetime1,datetime2))
    pe_table = pd.pivot_table(pe_index, values = 'Value', index = 'Symbol', columns = 'StdDateTime')
    pe_select = pe_table[pe_table[pe_table.columns[0]] < 12]
    pe_select.columns = ['pe']

    select = pd.concat([pb_select, pe_select], axis = 1).dropna(how = 'any')

    return select.index

stocklist = GetMonthlyStock(Year = 2017, Month = 5)
print (stocklist)

#a = pd.DataFrame(pe_index)
#b = pd.pivot_table(a, values = 'Value', index = 'Symbol', columns = 'StdDateTime')
#a.to_csv('D:/myfile/test5.csv', encoding = 'GBK')
#sz_index = database.find("Future", "A1709.DCE_Time_86400_Bar", datetime1,datetime2)
#print (a.head())